'use strict';
define('service', ['app'], function (app) {

    // 用户交互相关
    app.factory('UI', [function () {

        var service = {};

        service.loading = {
            cnt: 0,
            on: function () {
                var o = $('#status-loading');
                service.loading.cnt++;
                o.css({
                    left: ($(window).width() - $(o).width()) / 2 + 'px'
                }).css({
                    visibility: 'visible'
                });
            },
            off: function () {
                service.loading.cnt--;
                if (service.loading.cnt <= 0) {
                    $('#status-loading').css({
                        visibility: 'hidden'
                    });
                }
            }
        };

        service.success = {
            timeout: null,
            show: function (text) {
                var o = $('#status-success');
                o.html(text).css({
                    left: ($(window).width() - $(o).width()) / 2 + 'px'
                }).css({
                    visibility: 'visible'
                });
                if (service.success.timeout) {
                    clearTimeout(service.success.timeout);
                }
                service.success.timeout = setTimeout(function () {
                    o.css({
                        visibility: 'hidden'
                    });
                }, 1500);
            }
        };

        service.error = {
            timeout: null,
            show: function (text) {
                var o = $('#status-error');
                o.html(text).css({
                    left: ($(window).width() - $(o).width()) / 2 + 'px'
                }).css({
                    visibility: 'visible'
                });
                if (service.error.timeout) {
                    clearTimeout(service.error.timeout);
                }
                service.error.timeout = setTimeout(function () {
                    o.css({
                        visibility: 'hidden'
                    });
                }, 1500);
            }
        };

        return service;
    }]);

    app.service('SystemService', [function () {
        var service = {
            config: System
        };
        return service;
    }]);

    app.service('ResponseChecker', ['$location', function ($location) {
        var service = {
            callback: function (data) {
                if (data.status == 0) {
                    if (data.info == 'login_required') {
                        window.location.href = TPX.PATH_ROOT + '/#/login';
                        return;
                    } else if (data.info == 'login_success') {
                        window.location.href = TPX.PATH_ROOT + '/';
                        return;
                    }
                }
                $.defaultFormCallback(data);
            }
        };
        return service;
    }]);

    app.service('UserService', ['ResponseChecker', 'UI', function (responseChecker, ui) {
        var service = {
            user: User,
            data: {
                username: '',
                upload_space_space: '0 MB',
                upload_space_used: '0 MB',
                profile_realname: '',
                doc_header_image: ''
            },
            init: function () {
                if (service.user.logined) {
                    ui.loading.on();
                    $.post($.urlBuild('user', 'load_profile'), {}, function (data) {
                        ui.loading.off();
                        if (data.status == 1) {
                            service.data.username = data.data.username;
                            service.data.upload_space_space = data.data.upload_space_space;
                            service.data.upload_space_used = data.data.upload_space_used;
                            service.data.profile_realname = data.data.profile_realname;
                            service.data.doc_header_image = data.data.doc_header_image;
                        } else {
                            responseChecker.callback(data);
                        }
                    });
                }
            },
            submitProfile: function () {
                ui.loading.on();
                $.post($.urlBuild('user', 'profile'), service.data, function (data) {
                    ui.loading.off();
                    if (data.status == 1) {
                        ui.success.show('更新成功');
                    } else {
                        responseChecker.callback(data);
                    }
                });
            }
        };
        service.init();
        return service;
    }]);

    app.service('DocDraftService', ['DocService', function (docService) {
        var service = {
            key: function () {
                return 'doc{id:' + docService.one.id + '}';
            },
            checkAndNotice: function () {
                var draft = $.localStorage(service.key());
                if (null !== draft) {
                    $.dialog.confirm('上次有未保存的草稿，是否需要恢复', function () {
                        service.restore();
                    }, function (e) {
                        service.clear();
                    });
                }
            },
            restore: function () {
                var draft = $.localStorage(service.key());
                service.clear();
                if (null !== draft) {
                    docService.setMarkdown(draft);
                }
            },
            clear: function () {
                $.localStorage(service.key(), null);
            },
            save: function () {
                var content = docService.getMarkdown();
                if (content && content != docService.one.content) {
                    $.localStorage(service.key(), content);
                }
            },
            register: function () {
                setInterval(function () {
                    service.save();
                }, 5000);
            }
        };
        service.register();
        return service;
    }]);

    app.service('DocService', ['$sce', 'ResponseChecker', 'UI', function ($sce, responseChecker, ui) {
        var service = {
            listScope: null,
            bodyScope: null,
            url: '',
            data: [],
            search: {
                keywords: ''
            },
            one: {
                id: 0,
                out_id: '',
                cat_id: 0,
                title: '',
                content: '',
                wp_id: 0
            },
            // 删除
            delete: function (id, callback) {
                callback = callback || null;
                if (!id) {
                    ui.error.show('文档为空');
                    return;
                }
                ui.loading.on();
                $.post($.urlBuild('doc', 'delete'), {id: id}, function (data) {
                    ui.loading.off();
                    if (data.status == 1) {
                        if (id == service.one.id) {
                            // 删除了当前打开的文档
                            service.one.id = 0;
                            service.one.out_id = '';
                            var cat_id = service.one.cat_id;
                            service.one.cat_id = 0;
                            service.one.title = '';
                            service.one.content = '';
                            service.setMarkdown('');
                            service.fetch(cat_id, 1);
                        } else {
                            // 删除了其他文档
                            var cat_id = data.data.cat_id;
                            service.fetch(cat_id, 1);
                        }
                        ui.success.show('删除成功');
                        if (service.bodyScope) {
                            service.bodyScope.$apply();
                        }
                        if (callback) {
                            callback();
                        }
                    } else {
                        responseChecker.callback(data);
                    }
                });
            },
            // 提交
            submit_loading: false,
            submit: function (callback) {
                if (service.submit_loading) {
                    return;
                }
                service.submit_loading = true;
                callback = callback || null;
                service.one.content = service.getMarkdown();
                if (!service.one.cat_id) {
                    ui.error.show('文档分类未选择');
                    service.submit_loading = false;
                    return;
                }
                if (!service.one.title) {
                    ui.error.show('文档标题为空');
                    service.submit_loading = false;
                    return;
                }
                if (!service.one.content) {
                    ui.error.show('文档内容为空');
                    service.submit_loading = false;
                    return;
                }
                var url = $.urlBuild('doc', 'add');
                if (service.one.id) {
                    url = $.urlBuild('doc', 'edit');
                }

                ui.loading.on();
                $.post(url, service.one, function (data) {
                    ui.loading.off();
                    service.submit_loading = false;
                    if (data.status == 1) {
                        service.one.id = data.data.id;
                        service.one.out_id = data.data.out_id;
                        service.one.update_time = data.data.update_time;
                        ui.success.show('保存成功');
                        if (service.bodyScope) {
                            service.bodyScope.$apply();
                        }
                        service.fetch(service.one.cat_id, 1);
                        if (callback) {
                            callback();
                        }
                    } else {
                        responseChecker.callback(data);
                    }
                });
            },
            // 加载
            load: function (id, callback) {
                if (id == 0) {
                    service.one.id = 0;
                    service.one.cat_id = service.cat_id;
                    service.one.title = '';
                    service.one.out_id = '';
                    service.one.content = '';
                    service.one.wp_id = 0;
                    service.setMarkdown('');
                    callback();
                    return;
                }
                ui.loading.on();
                $.post($.urlBuild('doc', 'load'), {id: id}, function (data) {
                    ui.loading.off();
                    if (data.status == 1) {
                        service.one = data.data;
                        service.setMarkdown(service.one.content);
                        callback();
                    } else {
                        responseChecker.callback(data);
                    }
                });

            },
            // 获取列表
            fetch_page: 1,
            fetch_end: false,
            fetch_cat_id: 0,
            fetch_loading: false,
            cat_id: 0,
            fetch: function (cat_id, page) {
                if (service.fetch_loading) {
                    return;
                }
                if (typeof cat_id == 'undefined') {
                    cat_id = service.fetch_cat_id;
                }
                if (typeof page == 'undefined') {
                    service.fetch_page++;
                    page = service.fetch_page;
                } else {
                    service.fetch_page = 1;
                    service.fetch_end = false;
                    service.fetch_cat_id = cat_id;
                    $('.list-loading').show();
                }
                service.fetch_loading = true;
                if (service.fetch_end) {
                    service.fetch_loading = false;
                    return;
                }
                ui.loading.on();
                $.post($.urlBuild('doc', 'fetchall'), {
                    cat_id: service.fetch_cat_id,
                    page: page,
                    search: service.search
                }, function (data) {
                    ui.loading.off();
                    if (data.status == 1) {
                        service.cat_id = cat_id;
                        if (data.list.length == 0) {
                            if (page == 1) {
                                service.data = [];
                            }
                            service.fetch_end = true;
                        } else {
                            if (page == 1) {
                                service.data = [];
                            }
                            for (var i = 0; i < data.list.length; i++) {
                                service.data.push(data.list[i]);
                            }
                        }
                        if (!data.hasMore) {
                            $('.list-loading').hide();
                        }
                        if (service.listScope) {
                            service.listScope.$apply();
                        }
                    } else {
                        responseChecker.callback(data);
                    }
                    service.fetch_loading = false;
                });
            },
            setMarkdown: function (m) {
                if (!markdownEditor) {
                    // 没有加载完成，推迟放值
                    setTimeout(function () {
                        service.setMarkdown(m);
                    }, 100);
                    return;
                }
                markdownEditor.setMarkdown(m);
            },
            getMarkdown: function () {
                if (!markdownEditor) {
                    return '';
                }
                return markdownEditor.getMarkdown();
            },
            fullscreenMarkdown: function () {
                if (!markdownEditor) {
                    return;
                }
                markdownEditor.fullscreen().fullscreen();
            },
            history_data: [],
            fetch_history: function () {
                ui.loading.on();
                $.post($.urlBuild('doc', 'fetch_history'), {id: service.one.id}, function (data) {
                    ui.loading.off();
                    if (data.status == 1) {

                        if (data.list.length > 0 && data.list[0].content != service.getMarkdown()) {
                            service.history_data = []
                            service.history_data.push({
                                id: -1,
                                update_time: '未保存版本',
                                content: service.getMarkdown()
                            });
                            for (var i = 0; i < data.list.length; i++) {
                                service.history_data.push(data.list[i]);
                            }
                        } else {
                            service.history_data = data.list;
                        }

                        var dmp = new diff_match_patch();
                        var i = 0, diff;
                        for (; i < service.history_data.length; i++) {
                            if (i == service.history_data.length - 1) {
                                diff = dmp.diff_main("", service.history_data[i].content);
                            } else {
                                diff = dmp.diff_main(service.history_data[i + 1].content, service.history_data[i].content);
                            }
                            dmp.diff_cleanupSemantic(diff);
                            service.history_data[i].content_diff = dmp.diff_prettyHtml(diff);
                        }

                        service.history_data = angular.forEach(angular.fromJson(service.history_data), function (post) {
                            post.content_diff = $sce.trustAsHtml(post.content_diff);
                        });

                        if (service.bodyScope) {
                            service.bodyScope.$apply();
                        }
                        // 显示弹出框
                        $('#body-history .modal-dialog').css({
                            width: ($(window).width() > 800 ? 800 : $(window).width()) + 'px'
                        });
                        $('#body-history').modal();

                    } else {
                        responseChecker.callback(data);
                    }
                });
            },
            restore_history: function (id) {
                for (var i = 0; i < service.history_data.length; i++) {
                    if (service.history_data[i].id == id) {
                        var d = service.history_data[i];
                        service.setMarkdown(d.content);
                        $('#body-history').modal('hide');
                        ui.success.show('成功恢复 ' + d.update_time + ' 的历史记录到编辑器');
                        return;
                    }
                }
                ui.error.show('没有找到ID为 ' + id + ' 的历史记录');
            },
            wordpress_submit: function (categorys, success_callback) {
                categorys = categorys || [];
                success_callback = success_callback || null;
                if (categorys.length == 0) {
                    ui.error.show('没有选择分类');
                    return;
                }
                var data = {};
                data.id = service.one.id;
                data.categorys = categorys;
                ui.loading.on();
                $.post($.urlBuild('doc', 'wordpress_publish'), data, function (data) {
                    ui.loading.off();
                    if (data.status == 1) {
                        ui.success.show('发布到Wordpress成功');
                        service.one.wp_id = data.data.wp_id;
                        success_callback();
                    } else {
                        responseChecker.callback(data);
                    }
                });
            },
            wordpress_sync: function (success_callback) {
                success_callback = success_callback || null;
                var data = {};
                data.id = service.one.id;
                ui.loading.on();
                $.post($.urlBuild('doc', 'wordpress_sync'), data, function (data) {
                    ui.loading.off();
                    if (data.status == 1) {
                        ui.success.show('同步到Wordpress成功');
                        success_callback();
                    } else {
                        responseChecker.callback(data);
                    }
                });
            },
            wordpress_unlink: function (success_callback) {
                success_callback = success_callback || null;
                var data = {};
                data.id = service.one.id;
                ui.loading.on();
                $.post($.urlBuild('doc', 'wordpress_unlink'), data, function (data) {
                    ui.loading.off();
                    if (data.status == 1) {
                        service.one.wp_id = 0;
                        ui.success.show('解除关联Wordpress成功');
                        success_callback();
                    } else {
                        responseChecker.callback(data);
                    }
                });
            }

        };
        service.fetch(0, 1);
        return service;
    }]);


    app.service('DocCatService', ['$http', 'ResponseChecker', 'UI', function ($http, responseChecker, ui) {
        var service = {
            data: [],
            // 加载
            load: function (id) {
                for (var i = 0; i < service.data.length; i++) {
                    if (service.data[i].id == id) {
                        return service.data[i];
                    }
                }
                return null;
            },
            // 添加
            add: function (cat, callback) {
                ui.loading.on();
                $.post($.urlBuild('doc_cat', 'add'), cat, function (data) {
                    ui.loading.off();
                    callback(data);
                });
            },
            // 更新
            edit: function (cat, callback) {
                ui.loading.on();
                $.post($.urlBuild('doc_cat', 'edit'), cat, function (data) {
                    ui.loading.off();
                    callback(data);
                });
            },
            // 删除
            delete: function (cat, callback) {
                ui.loading.on();
                $.post($.urlBuild('doc_cat', 'delete'), cat, function (data) {
                    ui.loading.off();
                    callback(data);
                });
            },
            reload: function (callback) {
                callback = callback || null;
                ui.loading.on();
                $.post($.urlBuild('doc_cat', 'fetchall'), {}, function (data) {
                    ui.loading.off();
                    if (data.status == 1) {
                        service.data = data.list;
                    } else {
                        responseChecker.callback(data);
                    }
                    if (callback) {
                        callback();
                    }
                });
            }
        };
        service.reload();
        return service;
    }]);

});